package eu.darken.octi.sync.module.syncs.jserver.core

import com.gitee.wsl.jvm.okio.fromGzip
import com.gitee.wsl.jvm.okio.toGzip
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapter
import eu.darken.octi.sync.core.encryption.PayloadEncryption
import okio.ByteString.Companion.decodeBase64
import okio.ByteString.Companion.toByteString

@JsonClass(generateAdapter = true)
data class LinkingData(
    @Json(name = "serverAddress") val serverAdress: JServer.Address,
    @Json(name = "shareCode") val linkCode: JServer.Credentials.LinkCode,
    @Json(name = "encryptionKeySet") val encryptionKeyset: PayloadEncryption.KeySet,
) {

    @OptIn(ExperimentalStdlibApi::class)
    fun toEncodedString(moshi: Moshi): String = moshi.adapter<LinkingData>()
        .toJson(this)
        .toByteArray()
        .toByteString()
        .toGzip()
        .base64()

    companion object {
        @OptIn(ExperimentalStdlibApi::class)
        fun fromEncodedString(moshi: Moshi, encoded: String): LinkingData = encoded
            .decodeBase64()!!
            .fromGzip()
            .let { moshi.adapter<LinkingData>().fromJson(it.utf8())!! }
    }
}